package com.blog.service.impl;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;  
import java.util.Collection;  
import java.util.List;  
  




import javax.annotation.Resource;  
  




import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;  
import org.springframework.security.core.authority.*;  
import org.springframework.security.core.userdetails.User;  
import org.springframework.security.core.userdetails.UserDetails;  
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;  
import org.springframework.stereotype.Service;  

import com.blog.dao.UserPoJoMapper;
import com.blog.model.UserPoJo;
import com.blog.service.interfaces.CustomUserDetailService;

  

  
/**  
 * TODO(这里用一句话描述这个类的职责). 
 * @ClassName: CustomUserDetailsServiceImpl 
 * @author Johnny_L_Q 
 */  
@Service("customUserDetailsService")  
public class CustomUserDetailServiceImpl implements CustomUserDetailService,UserDetailsService  {  
  
    /** 
     * @Fields serialVersionUID : TODO（用一句话描述这个变量表示什么）. 
     */  
    private static final long serialVersionUID = 1L;  
      
    @Autowired 
    private UserPoJoMapper userPoJoMapper;  
      
  
    /* 
     * 根据用户名判断是否存在 
     * <p>Title: loadUserByUsername</p> 
     * <p>Description: </p> 
     * @param arg0 
     * @return 
     * @throws UsernameNotFoundException 
     * @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
     *  loadUserByUsername 传入一个用户名，功能是查找该用户名对应的密码，权限 并传回给security，security与输入的密码作对比
     */  
    
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {  
		
		try {
			username=new String(username.getBytes("ISO-8859-1"), "utf8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		System.out.println(username);
    	UserPoJo userpojo=userPoJoMapper.selectByName(username);
        if (null == userpojo) {  
            throw new UsernameNotFoundException("用户" + username + "不存在");  
        }  
        String passWord=PublicUtil.decrypt(userpojo.getPassword());  
        Integer group=userpojo.getGroup();
        
        System.out.println(username);
		System.out.println(userpojo.getPassword());
		System.out.println(passWord);
		
        Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>(); 
        //增加权限  0 管理员 1 一般用户 2 匿名用户
        if(group==0){ auths.add(new SimpleGrantedAuthority("ROLE_ADMIN"));auths.add(new SimpleGrantedAuthority("ROLE_USER"));}
        if(group==1){ auths.add(new SimpleGrantedAuthority("ROLE_USER"));}

        //因为UserEntity实现了UserDetails，所以也可以直接返回user  
        return new User(username, passWord, true, true, true, true, auths);  
    }  
  
}  
